package com.vgooo.client;

import java.lang.reflect.Field;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.NotificationType;
import com.umeng.fb.UMFeedbackService;
import com.umeng.update.UmengDownloadListener;
import com.umeng.update.UmengUpdateAgent;
import com.vgooo.bean.UserInfo;
import com.vgooo.client.myvg.UserUtils;
import com.vgooo.util.DebugTools;
import com.vgooo.util.Utils;

public class LoadingActivity extends Activity {
	private final static int NONE = 0;
	private final static int NET_SET = 1;
	private String version = "Verison 1.0.0";

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		// 设置缓存路径
		VGApplication appliction = (VGApplication) getApplication();
		appliction.setCaesPath(getCacheDir().toString());

		Window window = getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
		window.addFlags(WindowManager.LayoutParams.FLAG_DITHER);

		PackageManager pm = getPackageManager();
		try {
			PackageInfo pi = pm.getPackageInfo("com.vgooo.client", 0);
			version = "Verison " + pi.versionName;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		init();
		setContentView(R.layout.loading_layout);
		TextView versionNumber = (TextView) findViewById(R.id.ver_text);
		versionNumber.setText(version);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// 在欢迎界面屏蔽BACK键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		}
		return false;
	}

	private void init() {
		if (Utils.hasNetWork(this)) {
			startMain();

			// 设置缓存路径
			VGApplication appliction = (VGApplication) getApplication();
			appliction.setCaesPath(getCacheDir().toString());
			// 设置文件路径
			appliction.file = getFilesDir().toString();
			// 读取用户信息
			UserInfo user = UserUtils.readUserInfo(this);
			if (user != null) {
				VGApplication.userInfo = user;
			}

		} else {
			setNet();
		}
	}

	/**
	 * 启动程序主界面
	 */
	private void startMain() {
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Intent intent = new Intent(LoadingActivity.this, Main.class);
				LoadingActivity.this.startActivity(intent);
				LoadingActivity.this.finish();

			}
		}, 1000);
	}

	public Builder builder;
	private AlertDialog dialog;

	/**
	 * 设置网络
	 */
	private void setNet() {
		builder = new AlertDialog.Builder(this)
				.setTitle("找不到网络")
				.setMessage("连接网络失败，请检查网络")
				.setCancelable(false)
				.setPositiveButton("设置", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int buttonId) {
						switch (buttonId) {
						case DialogInterface.BUTTON_POSITIVE:
							try {
								Field field = builder.getClass()
										.getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								// 将mShowing变量设为false，表示对话框已关闭
								field.set(builder, false);

							} catch (Exception e) {
								e.printStackTrace();
							}
							Intent mIntent = new Intent(
									android.provider.Settings.ACTION_WIRELESS_SETTINGS);
							// mIntent.setAction(android.provider.Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
							LoadingActivity.this.startActivityForResult(
									mIntent, NET_SET);
							break;
						}

					}
				})

				.setNeutralButton("重试", new AlertDialog.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						// Static.builder = null;
						try {
							Field field = builder.getClass().getSuperclass()
									.getDeclaredField("mShowing");
							field.setAccessible(true);
							// 将mShowing变量设为false，表示对话框已关闭
							field.set(builder, true);
							// dialog.dismiss();

						} catch (Exception e) {
							e.printStackTrace();
						}

						dialog.cancel();
						init();
					}

				})
				.setNegativeButton("退出", new DialogInterface.OnClickListener() {
					@SuppressLint("NewApi")
					public void onClick(DialogInterface dialog, int id) {
						try {
							Field field = builder.getClass().getSuperclass()
									.getDeclaredField("mShowing");
							field.setAccessible(true);
							// 将mShowing变量设为false，表示对话框已关闭
							field.set(builder, true);
							// dialog.dismiss();

						} catch (Exception e) {
							e.printStackTrace();
						}
						// Static.isClose = true;
						// Static.back_key_times = 0;
						ActivityManager am;
						am = (ActivityManager) LoadingActivity.this
								.getSystemService(Service.ACTIVITY_SERVICE);
						finish();
						try {
							// Static.nm.cancel(Static.NOTIFICATION_ID);
						} catch (Exception e) {
						}
						if (Integer.valueOf(Build.VERSION.SDK) >= 8) {
							am.killBackgroundProcesses(getPackageName());
						}
						dialog.cancel();

					}
				})

		;

		dialog = builder.create();
		dialog.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == NET_SET) {
			init();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		View view = (View) findViewById(R.id.llayout);
		BitmapDrawable bd = (BitmapDrawable) view.getBackground();
		view.setBackgroundResource(R.drawable.bg_transparent);

		bd.setCallback(null);
		Bitmap bm = bd.getBitmap();
		if (bm != null && !bm.isRecycled()) {
			bm = null;
			bd = null;
		}
	}

}
